#target illustrator
(function () {
    if (app.documents.length === 0) { alert("请先打开一个文档。"); return; }
    var doc = app.activeDocument;
    if (!doc.selection || doc.selection.length === 0) { alert("请先选择要处理的对象或锚点。"); return; }

    var EPS = 1e-6;

    // —— 仅判断“开放路径且≥2点”，允许多点
    function isOpenPath(pi) {
        try {
            return pi && pi.typename === "PathItem" &&
                   !pi.guides && !pi.clipping && !pi.closed &&
                   pi.pathPoints && pi.pathPoints.length >= 2 &&
                   !pi.locked && !pi.hidden;
        } catch (e) { return false; }
    }

    // —— 只在当前选区内递归搜集目标，避免全文档遍历
    function collectTargets(selection) {
        var out = [], seen = {};
        function addUnique(item) {
            var key;
            try { key = item.uuid || item.id || item.toString(); } catch(e) { key = item.toString(); }
            if (!seen[key]) { seen[key] = true; out.push(item); }
        }
        function dig(it) {
            if (!it) return;

            if (it.typename === "PathPoint") { // 若只选了锚点，也能拿到父路径
                var pi = it.parent;
                if (isOpenPath(pi)) addUnique(pi);
                return;
            }
            if (it.typename === "PathItem") {
                if (isOpenPath(it)) addUnique(it);
                return;
            }
            if (it.typename === "GroupItem") {
                if (it.locked || it.hidden) return;
                var kids = it.pageItems;
                for (var i = 0; i < kids.length; i++) dig(kids[i]);
                return;
            }
            if (it.typename === "CompoundPathItem") {
                if (it.locked || it.hidden) return;
                var subs = it.pathItems;
                for (var j = 0; j < subs.length; j++) {
                    if (isOpenPath(subs[j])) addUnique(subs[j]);
                }
                return;
            }
            // 其他类型忽略
        }
        for (var i = 0; i < selection.length; i++) dig(selection[i]);
        return out;
    }

    // —— 在“首尾两端点”之间，按 X 判定哪边是左端/右端（X 近似相等时固定首=左、尾=右，稳定）
    function getEndsLeftRightIndex(pi) {
        var n = pi.pathPoints.length;
        var iL = 0, iR = n - 1;
        var aL = pi.pathPoints[iL].anchor;
        var aR = pi.pathPoints[iR].anchor;
        if (aL[0] < aR[0] - EPS) return { left: iL, right: iR };
        if (aL[0] > aR[0] + EPS) return { left: iR, right: iL };
        // X 基本相等，按“首为左、尾为右”兜底
        return { left: iL, right: iR };
    }

    var targets = collectTargets(doc.selection);
    if (targets.length === 0) { alert("未找到可处理的“开放路径（≥2点）”。"); return; }

    // —— 询问对齐方向：1=左对齐；2=右对齐
    var ans = prompt(
        "选择对齐方向：\n1) 左对齐（右端点不动；左端点对齐到所有目标左端(首尾较左者)的最小X，且Y=右端Y）\n2) 右对齐（左端点不动；右端点对齐到所有目标右端(首尾较右者)的最大X，且Y=左端Y）",
        "1"
    );
    ans = String(ans).replace(/^\s+|\s+$/g, "");
    if (ans !== "1" && ans !== "2") { alert("已取消或输入无效。请输入 1 或 2。"); return; }
    var alignLeft = (ans === "1");

    // —— 计算参考 X：
    // 左对齐：所有目标“首尾较左端”的 X 的最小值
    // 右对齐：所有目标“首尾较右端”的 X 的最大值
    var refX = null;
    for (var i = 0; i < targets.length; i++) {
        var p = targets[i];
        var lr = getEndsLeftRightIndex(p);
        var px = alignLeft ? p.pathPoints[lr.left].anchor[0]
                           : p.pathPoints[lr.right].anchor[0];
        if (refX === null || (alignLeft ? (px < refX) : (px > refX))) refX = px;
    }

    // —— 核心修改：仅动首尾端点；中间点不改
    var changed = 0, skipped = 0;
    for (var k = 0; k < targets.length; k++) {
        var pi = targets[k];
        try {
            var lr = getEndsLeftRightIndex(pi);
            var lp = pi.pathPoints[lr.left];
            var rp = pi.pathPoints[lr.right];

            if (alignLeft) {
                // 左对齐：右端点不动；左端点 X=refX，Y=右端点 Y
                var rightY = rp.anchor[1];
                var newLeft = [refX, rightY];
                lp.anchor = newLeft;
                lp.leftDirection = newLeft;
                lp.rightDirection = newLeft;
                lp.pointType = PointType.CORNER;

                var rAnc = [rp.anchor[0], rp.anchor[1]];
                rp.leftDirection = rAnc;  // 收把手，确保端段是直线
                rp.rightDirection = rAnc;
                rp.pointType = PointType.CORNER;
            } else {
                // 右对齐：左端点不动；右端点 X=refX，Y=左端点 Y
                var leftY = lp.anchor[1];
                var newRight = [refX, leftY];
                rp.anchor = newRight;
                rp.leftDirection = newRight;
                rp.rightDirection = newRight;
                rp.pointType = PointType.CORNER;

                var lAnc = [lp.anchor[0], lp.anchor[1]];
                lp.leftDirection = lAnc;
                lp.rightDirection = lAnc;
                lp.pointType = PointType.CORNER;
            }
            changed++;
        } catch (e) {
            skipped++;
        }
    }

    alert(
        (alignLeft ? "左对齐完成。" : "右对齐完成。") +
        "\n处理路径：" + changed +
        "\n跳过：" + skipped +
        "\n参考 X = " + (refX != null ? refX.toFixed(3) : "N/A") + " pt"
    );
})();
